<?php

namespace Kateba\SiteBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Kateba\SiteBundle\Entity\Message;
use Kateba\SiteBundle\Form\MessageType;

/**
 * Message controller.
 * @author Mahmoud
 */
class MessageController extends Controller {

    private function markMessagesAsRead($messages) {
        foreach ($messages as $message) {
            if ($message->getIsAdmin() && $message->getIsNew()) {
                $message->setIsNew(false);
            }
        }
        $this->getDoctrine()->getEntityManager()->flush();
    }

    public function userMessagesAction() {
        $user = $this->get('security.context')->getToken()->getUser();
        $maxResults = 10;
        $messages = $this->getDoctrine()->getRepository('KatebaSiteBundle:Message')->getLatestMessages($user->getId(), $maxResults + 1);
        $lastMessageId = 0;
        $firstMessageId = 0;
        $messagesCount = count($messages);
        if ($messagesCount > 0) {
            $lastMessageId = $messages[0]->getId();
            if ($messagesCount > $maxResults) {
                $firstMessageId = $messages[$maxResults - 1]->getId();
                array_pop($messages);
            }
        }
        $message = new Message();
        $message->setUser($user);
        $form = $this->createForm(new MessageType(), $message);
        $this->markMessagesAsRead($messages);
        return $this->render('KatebaSiteBundle:Message:userMessages.html.twig', array(
                    'messages' => array_reverse($messages),
                    'lastMessageId' => $lastMessageId,
                    'firstMessageId' => $firstMessageId,
                    'form' => $form->createView()
                ));
    }

    public function createAction(Request $request) {
        $user = $this->get('security.context')->getToken()->getUser();
        $message = new Message();
        $message->setUser($user);
        $form = $this->createForm(new MessageType(), $message);
        $form->bind($request);

        if ($form->isValid()) {
            $userNotify = $user->getMessageNotify();
            if ($request->get('notify') === 'on') {
                if (!$userNotify) {
                    $user->setMessageNotify(true);
                }
            } else {
                if ($userNotify) {
                    $user->setMessageNotify(false);
                }
            }
            $em = $this->getDoctrine()->getManager();
            $em->persist($message);
            $em->flush();
            $em->getRepository('KatebaUserBundle:User')->increaseNumbeerOfNewMessages($user->getId());
            // clear the form
            $message = new Message();
            $form = $this->createForm(new MessageType(), $message);
        }
        return $this->render('KatebaSiteBundle:Message:newUserMessageForm.html.twig', array(
                    'form' => $form->createView()
                ));
    }

    public function newUserMessagesAction($id) {
        $user = $this->get('security.context')->getToken()->getUser();
        $messages = $this->getDoctrine()->getRepository('KatebaSiteBundle:Message')->getNewerMessages($user->getId(), $id);
        $lastMessageId = $id;
        if (count($messages) > 0) {
            $lastMessageId = $messages[0]->getId();
            $messages = array_reverse($messages);
        }
        $this->markMessagesAsRead($messages);
        $data = array();
        $data['lastMessageId'] = $lastMessageId;
        $data['messages'] = $this->renderView('KatebaSiteBundle:Message:messages.html.twig', array('messages' => $messages));
        return new Response(json_encode($data), 200, array('Content-Type' => 'application/json'));
    }

    public function oldUserMessagesAction($id) {
        $user = $this->get('security.context')->getToken()->getUser();
        $maxResults = 10;
        $messages = $this->getDoctrine()->getRepository('KatebaSiteBundle:Message')->getOlderMessages($user->getId(), $id, $maxResults + 1);
        $firstMessageId = 0;
        $messagesCount = count($messages);
        if ($messagesCount > 0) {
            $messages = array_reverse($messages);
            if ($messagesCount > $maxResults) {
                array_shift($messages);
                $firstMessageId = $messages[0]->getId();
            }
        }
        $this->markMessagesAsRead($messages);
        $data = array();
        $data['firstMessageId'] = $firstMessageId;
        $data['messages'] = $this->renderView('KatebaSiteBundle:Message:messages.html.twig', array('messages' => $messages));
        return new Response(json_encode($data), 200, array('Content-Type' => 'application/json'));
    }

    public function getUnreadMessagesCountAction() {
        if (FALSE === $this->get('security.context')->isGranted('ROLE_NOTACTIVE')) {
            return new Response('0');
        }
        $user = $this->get('security.context')->getToken()->getUser();
        return new Response($this->getDoctrine()->getRepository('KatebaSiteBundle:Message')->getUserUnreadMessagesCount($user->getId()));
    }

    public function getNewMessagesCountAction($id) {
        $user = $this->get('security.context')->getToken()->getUser();
        return new Response($this->getDoctrine()->getRepository('KatebaSiteBundle:Message')->getNewerMessagesCount($user->getId(), $id));
    }

}
